package logic

import (
	"context"
	"shop-ease/internal/cache"
	"strconv"

	"shop-ease/shopRpc/internal/svc"
	"shop-ease/shopRpc/shopRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartListLogic {
	return &CartListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartListLogic) CartList(in *shopRpc.CartListRequest) (*shopRpc.CartListResponse, error) {
	// 购物车列表
	cartLists := cache.CartList(in.UserId)
	var lists []*shopRpc.CartList
	total := 0.0
	for _, list := range cartLists {
		listItem := cache.RDB.HGetAll(l.ctx, list).Val()
		price, _ := strconv.ParseFloat(listItem["price"], 64)
		quantity, _ := strconv.Atoi(listItem["quantity"])
		cartList := shopRpc.CartList{
			Name:     listItem["name"],
			Price:    float32(price),
			Quantity: int64(quantity),
		}
		lists = append(lists, &cartList)
		total += price * float64(quantity)
	}
	return &shopRpc.CartListResponse{
		Total: float32(total),
		List:  lists,
	}, nil
}
